package cn.tedu.service;

import cn.tedu.domain.ErrorResult;
import cn.tedu.domain.User;
import cn.tedu.exception.BusinessException;
import cn.tedu.mapper.UserMapper;
import cn.tedu.util.FaceUtil;
import cn.tedu.util.OssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
//更新用户头像
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private OssUtil ossUtil;

    @Autowired
    private FaceUtil FaceUtil;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //1、将图片上传到阿里云oss
        String imageUrl = ossUtil.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2、调用百度云判断是否包含人脸
        boolean detect = FaceUtil.detect(imageUrl);
        //2.1 如果不包含人脸，抛出异常
        if (!detect) {
            throw new BusinessException(ErrorResult.faceError());
        } else {
            //2.2 包含人脸，调用API更新
            User user = new User();
            user.setId(id);
            user.setAvatar(imageUrl);
            userMapper.updateById(user);
        }
    }
}
